package com.zprmb.udzt;

import java.text.DecimalFormat;

import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;


public class V4UpMoneyActivity extends BaseActivity implements OnClickListener{

	
	private ImageView iv_v4_upmoney_back;
	private TextView tv_v4_upmoney_title;
	private TextView tv_v4_upmoney_keyong;
	private ImageView iv_v4_upmoney_bankioc;
	private TextView tv_v4_upmoney_bankname;
	private TextView tv_v4_upmoney_banknum;
	private EditText et_v4_upmoney_jine,et_code,et_pwd;
	private TextView tv_v4_upmoney_up;
	private RelativeLayout rl_back;
	private ImageView iv_v4_upmoney,pass;
	private TextView tv_customer;
	private WebView wv;
	
	private double availableAmount;
	private Button btn_send_mes;
	private TextView tv_forget;
	DecimalFormat df = new DecimalFormat("###0.00");
	private MyCount myCount = new MyCount(60000, 1000);
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.v4_upmoney_activity);
		 BbtApplication.getInstance().addActvity(this);
		if (getShare().getInt("ss", 9527) == 9527) {
			Editor editor = getShare().edit();
			editor.putInt("ICBC", R.drawable.bbt_icbc);
			editor.putInt("ABC", R.drawable.bbt_abc);
			editor.putInt("BOC", R.drawable.bbt_boc);
			editor.putInt("CCB", R.drawable.bbt_ccb);
			editor.putInt("CMB", R.drawable.bbt_cbm);
			editor.putInt("CEB", R.drawable.bbt_ceb);
			editor.putInt("SPDB", R.drawable.bbt_spdb);
			editor.putInt("CIB", R.drawable.bbt_cib);
			editor.putInt("PSBC", R.drawable.bbt_psbc);
			editor.putInt("HXB", R.drawable.bbt_hxb);
			editor.putInt("BCCB", R.drawable.bbt_bccb);
			editor.putInt("BOS", R.drawable.bbt_bos);
			editor.putInt("CGB", R.drawable.bbt_cgb);
			editor.putInt("CMSB", R.drawable.bbt_cmsb);
			editor.putInt("CNCB", R.drawable.bbt_cncb);
			editor.putInt("COMM", R.drawable.bbt_comm);
			editor.putInt("HZCB", R.drawable.bbt_hzcb);
			editor.putInt("NBCB", R.drawable.bbt_nbcb);
			editor.putInt("PAB", R.drawable.bbt_pab);
			editor.putInt("BCCB", R.drawable.bbt_bccb);
			editor.putInt("ss", 1);
			editor.commit();
		}
		Log.e("spdb",getShare().getInt("ss", 9527) +"");
		initView();
		initDate();
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}
	private void initDate(){
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				if (jsonObject.optInt("success")==1) {
					Log.e("提现信息", jsonObject.toString());
					JSONObject json = jsonObject.optJSONObject("data");
					availableAmount = json.optDouble("availableAmount");
					tv_v4_upmoney_keyong.setText(df.format(Double.parseDouble(json.optString("availableAmount"))));
					BbtApplication.getInstance().display("https://rmbboximage.b0.upaiyun.com/bank/"+json.optString("bankNameEn")+".png", iv_v4_upmoney_bankioc);
//					iv_v4_upmoney_bankioc.setImageResource(getShare().getInt(json.optString("bankNameEn"), 0));
//					Log.e("spdb",json.optString("bankNameEn"));
					tv_v4_upmoney_banknum.setText("尾号"+json.optString("cardNo").substring(json.optString("cardNo").length()-4, json.optString("cardNo").length()));
				}else {
					if (jsonObject.optString("comment").equals("please login")) {
						Intent intent = new Intent(V4UpMoneyActivity.this,LoginActivity.class);
						startActivity(intent);
					}
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		vollery.setShow(false);
		vollery.setHeaders("token", getToken());
		vollery.setHeaders("client", "android");
		vollery.setRequestMethod(0);
		vollery.execute(this, Constant.URL+"apiAccount/userInfo", "");
	}

	private void initView() {
		iv_v4_upmoney_back = (ImageView) findViewById(R.id.img_back);
		iv_v4_upmoney_back.setOnClickListener(this);
		iv_v4_upmoney_bankioc = (ImageView) findViewById(R.id.iv_v4_upmoney_bankioc);
		et_v4_upmoney_jine = (EditText) findViewById(R.id.et_v4_upmoney_jine);
		tv_v4_upmoney_title = (TextView) findViewById(R.id.tv_v4_upmoney_title);
		tv_v4_upmoney_title.getPaint().setFakeBoldText(true);
		wv=(WebView)findViewById(R.id.wv);
		
		et_code=(EditText)findViewById(R.id.et_v4_upmoney_code);
		et_pwd=(EditText)findViewById(R.id.et_v4_upmoney_pwd);
		tv_v4_upmoney_title.setText("提现");
		tv_forget=(TextView)findViewById(R.id.tv_forget);
		btn_send_mes=(Button)findViewById(R.id.btn_send_mes);
		tv_v4_upmoney_keyong = (TextView) findViewById(R.id.tv_v4_upmoney_keyong);
		pass=(ImageView)findViewById(R.id.img_pass);
		tv_v4_upmoney_banknum = (TextView) findViewById(R.id.tv_v4_upmoney_banknum);
		tv_v4_upmoney_up = (TextView) findViewById(R.id.tv_v4_upmoney_up);
		tv_customer=(TextView)findViewById(R.id.enterprise_tel);
		rl_back=(RelativeLayout)findViewById(R.id.rl_back);
		rl_back.setOnClickListener(this);
		tv_customer.setOnClickListener(this);
		tv_v4_upmoney_up.setOnClickListener(this);
		pass.setOnClickListener(this);
		btn_send_mes.setOnClickListener(this);
		tv_forget.setOnClickListener(this);
		//LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(GetWindowWidth.getWidth(this), GetWindowWidth.getWidth(this)/5);
		
		//iv_v4_upmoney.setLayoutParams(ll);
		
        wv.loadUrl(Constant.URL+"/h5/withdrawRule?app=true");
		wv.getSettings().setSupportZoom(true);   
		wv.getSettings().setUseWideViewPort(true);
		wv.getSettings().setLoadWithOverviewMode(true);    
		wv.getSettings().setSavePassword(true);  
		wv.getSettings().setSaveFormData(true);
		wv.getSettings().setJavaScriptEnabled(true);    
		// enable navigator.geolocation   
		wv.getSettings().setGeolocationEnabled(true);     
		wv.getSettings().setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");    
		// enable Web Storage: localStorage, sessionStorage   
		wv.getSettings().setDomStorageEnabled(true);
		wv.requestFocus(); 
		wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//		v4_webview.setScrollBarStyle(0);
		String ua = wv.getSettings().getUserAgentString();
		wv.getSettings().setUserAgentString(ua+"; "+"rmbbox_android");
		
		wv.getSettings().setBuiltInZoomControls(true);
		wv.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		wv.getSettings().setDomStorageEnabled(true);  
		   // Set cache size to 8 mb by default. should be more than enough  
		wv.getSettings().setAppCacheMaxSize(1024*1024*8);  
		   // This next one is crazy. It's the DEFAULT location for your app's cache  
		   // But it didn't work for me without this line.  
		   // UPDATE: no hardcoded path. Thanks to Kevin Hawkins  
		   String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();  
		   
		   wv.getSettings().setAllowFileAccess(true);  
		   wv.getSettings().setAppCacheEnabled(true);
		   wv.getSettings().setJavaScriptEnabled(true);
		   wv.getSettings().setAppCachePath(appCachePath);
		   wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		   wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		   wv.getSettings().setSupportZoom(true); 
		   wv.getSettings().setDefaultTextEncodingName("utf-8");
		wv.setWebViewClient(new WebViewClient(){
			public boolean shouldOverrideUrlLoading(WebView view, String url){ 
				view.loadUrl(url);
				

				return true;
			}
			public void onReceivedSslError(WebView view,SslErrorHandler handler, SslError error) {
				//super.onReceivedSslError(view, handler, error);
				handler.proceed();
			}
		});
		/**
		 * 监听输入框，小数点后只能输入2位
		 */
		et_pwd.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(et_pwd.getText().toString().equals("")){
					pass.setVisibility(View.GONE);
				}else{
					pass.setVisibility(View.VISIBLE);
				}
			}
		});
		et_v4_upmoney_jine.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        et_v4_upmoney_jine.setText(s);
                        et_v4_upmoney_jine.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    et_v4_upmoney_jine.setText(s);
                    et_v4_upmoney_jine.setSelection(2);
                }
 
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                    	et_v4_upmoney_jine.setText(s.subSequence(0, 1));
                    	et_v4_upmoney_jine.setSelection(1);
                        return;
                    }
                }
            }
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }
            public void afterTextChanged(Editable s) {
            }
        });
	}
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:
			finish();
			break;
		
		case R.id.tv_v4_upmoney_up:
			if (et_v4_upmoney_jine.getText().toString().equals("")) {
				ToastUtil.showCenterToast(this, "请输入提现金额");
				return;
			}
//			try {
//				if (Double.valueOf(et_v4_upmoney_jine.getText().toString())<5) {
//					ToastUtil.showCenterToast(this, "提现金额不得小于5元");
//					return;
//				}
//			} catch (NumberFormatException e) {
//				e.printStackTrace();
//				ToastUtil.showCenterToast(this, "提现金额错误,请重新输入");
//				return;
//			}
			if (Double.valueOf(et_v4_upmoney_jine.getText().toString())>availableAmount) {
				ToastUtil.showCenterToast(this, "可用余额不足");
				return;
			}
			tv_v4_upmoney_up.setEnabled(false);
			upMoneyToBankCard(et_pwd.getText().toString(), et_code.getText().toString(), et_v4_upmoney_jine.getText().toString());
			break;
		case R.id.btn_send_mes:
			
			initSms();
			break;
		case R.id.tv_forget:
			Intent intent=new Intent(V4UpMoneyActivity.this,Reset_pwd_Mes.class);
			startActivity(intent);
			break;
		case R.id.img_pass:
			if(et_pwd.getTransformationMethod().equals(PasswordTransformationMethod  
                    .getInstance())){
				et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				pass.setBackgroundResource(R.drawable.yan1);
			}else{
				et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
				pass.setBackgroundResource(R.drawable.yan2);
			}
			break;

		case R.id.enterprise_tel:
			BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);
			break;
		case R.id.rl_back:
			finish();
			break;
		}
	}
	
	
	
	
	/**
	 * 提现请求
	 */
	private void upMoneyToBankCard(String payPass,String mobileCaptcha,String amount){
		AjaxParams params = new AjaxParams();
		params.put("payPass", payPass);
		params.put("mobileCaptcha", mobileCaptcha);
		params.put("amount", amount);
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				if (jsonObject.optInt("success")==1) {
					Intent intent = new Intent(V4UpMoneyActivity.this,SuccessActivity.class);
					tv_v4_upmoney_up.setEnabled(true);
					tv_v4_upmoney_up.setBackgroundResource(R.drawable.my_button);
					intent.putExtra("comment", jsonObject.optString("comment"));
					startActivity(intent);
					
					V4UpMoneyActivity.this.finish();
				}else {
					ToastUtil.showCenterToast(V4UpMoneyActivity.this, jsonObject.optString("comment"));
					tv_v4_upmoney_up.setEnabled(true);
					tv_v4_upmoney_up.setBackgroundResource(R.drawable.my_button);
				}
				Log.e("点击", "1");
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				tv_v4_upmoney_up.setEnabled(true);
				tv_v4_upmoney_up.setBackgroundResource(R.drawable.my_button);
				Intent intent=new Intent(V4UpMoneyActivity.this,V6ResultFinsh.class);
				intent.putExtra("title", "申请提现结果");
				
				intent.putExtra("description1", "您好，系统正在处理中，\n请3~5分钟之后前往 “我的账户”");
					
				
				intent.putExtra("description2", "确认提现结果！若申请失败请重新操作");
				intent.putExtra("button", "我的账户");
				startActivity(intent);
				V4UpMoneyActivity.this.finish();
			}
		};
		vollery.setHeaders("token", getToken());
		vollery.setHeaders("client", "android");
		vollery.setShow(true);
		vollery.execute(this, Constant.URL+"mpay/withdraw?", params.toString());
	}
	
	
	private void initSms(){
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				if (jsonObject.optInt("success")==1) {
					myCount.start();
					ToastUtil.showCenterToast(V4UpMoneyActivity.this, jsonObject.optString("comment"));
				}else {
					ToastUtil.showCenterToast(V4UpMoneyActivity.this, jsonObject.optString("comment"));
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		vollery.setShow(true);
		vollery.setHeaders("token", getToken());
		vollery.execute(this, Constant.URL+"/mpay/sendWithdrawMobileCaptcha", "");
	}
	 
	public class MyCount extends CountDownTimer {
		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		} 

		public void onFinish() { // 结束
			btn_send_mes.setText("获取验证码");
			btn_send_mes.setEnabled(true);
		} 

		public void onTick(long millisUntilFinished) { // 开始
			btn_send_mes.setText(millisUntilFinished / 1000 + "秒");
			btn_send_mes.setEnabled(false);
		}
	}
	
}
